<!--
* @Description: 图表
* @Version: 1.0.0
-->
<template>
  <div id="echarts" ref="chartRef" :style="echartsStyle"></div>
</template>

<script setup name="ECharts">
import * as echarts from "echarts";

/**
 * @description: props
 */
// const props = withDefaults(defineProps({ option: { type: Object } }), {
//   renderer: "canvas",
//   resize: true,
// });
const props = defineProps({ height: { type: Number }, option: { type: Object } });

/**
 * @description: 默认echarts样式
 */
const echartsStyle = computed(() => {
  return props.width || props.height ? { height: props.height + "px", width: props.width + "px" } : { height: "100%", width: "100%" };
});

// 图表dom
const chartRef = ref();
// echarts实例
const chartInstance = ref();

/**
 * @description: 监听props变化，重新绘制图表
 */
watch(props, () => {
  draw();
});

/**
 * @description: 绘制图表
 */
const draw = () => {
  if (chartInstance.value) {
    chartInstance.value.setOption(props.option, { notMerge: true });
  }
};

/**
 * @description: 点击事件
 * @param event 事件对象
 */
const handleClick = (event) => props.onClick && props.onClick(event);

/**
 * @description: 初始化echarts实例
 */
const init = () => {
  if (!chartRef.value) return;
  chartInstance.value = echarts.getInstanceByDom(chartRef.value);

  if (!chartInstance.value) {
    chartInstance.value = markRaw(
      echarts.init(chartRef.value, props.theme, {
        renderer: props.renderer,
      })
    );
    chartInstance.value.on("click", handleClick);
    draw();
  }
};

/**
 * @description: 监听窗口大小，重绘图表
 */
const resize = () => {
  if (chartInstance.value && props.resize) {
    chartInstance.value.resize({ animation: { duration: 300 } });
  }
};

onMounted(() => {
  nextTick(() => init());
});

onActivated(() => {
  if (chartInstance.value) {
    chartInstance.value.resize();
  }
});

onBeforeUnmount(() => {
  chartInstance.value?.dispose();
});

defineExpose({
  getInstance: () => chartInstance.value,
  resize,
  draw,
});
</script>
